package com.dcbeida.widget;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.dcbeida.R;
import com.dcbeida.widget.wheel.AbstractWheelTextAdapter;
import com.dcbeida.widget.wheel.OnWheelChangedListener;
import com.dcbeida.widget.wheel.OnWheelClickedListener;
import com.dcbeida.widget.wheel.WheelView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateSelectDialog extends Dialog implements OnWheelChangedListener,
        OnWheelClickedListener {

    private List<Integer> years;
    private List<Integer> months;
    private List<Integer> days;
    private int currentYear;
    private int currentMonth;
    private int currentDay;
    private Context mContext;

    private WheelView wheelView1;
    private WheelView wheelView2;
    private WheelView wheelView3;
    private String dd = "";

    public DateSelectDialog(Context context, DateSelectListener listener, String dd) {
        super(context, R.style.myDialogTheme);
        // TODO Auto-generated constructor stub
        mContext = context;
        this.dd = dd;
        initData();
        initView(context, listener);
    }

    private void initData() {
        // 初始化年，从1900年到2050年
        years = new ArrayList<Integer>();
        for (int i = 1900; i <= 2050; i++) {
            years.add(i);
        }

        // 初始化月
        months = new ArrayList<Integer>();
        for (int i = 1; i <= 12; i++) {
            months.add(i);
        }

        days = new ArrayList<Integer>();
    }

    private void initView(Context context, final DateSelectListener listener) {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_date_selecter, null);

        layout.findViewById(R.id.tvCancl).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        cancel();
                    }
                });

        // 用于回调确定方法
        layout.findViewById(R.id.tvConfirm).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        try {
                            String dateStr = getDateStr();
                            SimpleDateFormat format = new SimpleDateFormat(
                                    "yyyy-MM-dd");
                            Date date = format.parse(dateStr);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            listener.dateSelect(calendar);
                            cancel();
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });

        setContentView(layout);

        wheelView1 = (WheelView) layout.findViewById(R.id.wheelview1);
        wheelView1.setVisibleItems(5);
        wheelView1.setWheelBackground(R.drawable.wheel_bg_holo);
        wheelView1.setWheelForeground(R.drawable.wheel_val_holo);
        // wheelView1.setShadowColor(0xFF000000, 0x88000000, 0x00000000);
        wheelView1.setViewAdapter(new MyWheelAdapter(context, years, 1));
        wheelView1.addClickingListener(this);
        wheelView1.addChangingListener(this);

        wheelView2 = (WheelView) layout.findViewById(R.id.wheelview2);
        wheelView2.setVisibleItems(5);
        wheelView2.setWheelBackground(R.drawable.wheel_bg_holo);
        wheelView2.setWheelForeground(R.drawable.wheel_val_holo);
        // wheelView2.setShadowColor(0xFF000000, 0x88000000, 0x00000000);
        wheelView2.setViewAdapter(new MyWheelAdapter(context, months, 2));
        wheelView2.addClickingListener(this);
        wheelView2.addChangingListener(this);

        wheelView3 = (WheelView) layout.findViewById(R.id.wheelview3);
        wheelView3.setVisibleItems(5);
        wheelView3.setWheelBackground(R.drawable.wheel_bg_holo);
        wheelView3.setWheelForeground(R.drawable.wheel_val_holo);
        // wheelView2.setShadowColor(0xFF000000, 0x88000000, 0x00000000);
        wheelView3.setViewAdapter(new MyWheelAdapter(context, days, 3));
        wheelView3.addClickingListener(this);
        wheelView3.addChangingListener(this);
        if (!TextUtils.isEmpty(dd)) {
            wheelView3.setVisibility(View.GONE);
        } else {
            wheelView3.setVisibility(View.VISIBLE);
        }
        // 设置对话框的出现位置，借助于window对象
        Window win = getWindow();
        win.setGravity(Gravity.BOTTOM);
        // win.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//
        // 弹出对话框时，底部窗体，不变暗。

        WindowManager.LayoutParams lp = win.getAttributes();
        // lp.x = -200;// x=0,y=0时，显示位置是屏幕中心。
        // lp.y = 0;
        // lp.alpha = 0.6f;// 对话框的透明度
        lp.width = android.view.WindowManager.LayoutParams.MATCH_PARENT;
        win.setAttributes(lp);
        win.setWindowAnimations(R.style.dialoganimstyle);
        setCancelable(true);
    }

    public void setDate(Calendar calendar) {
        this.currentYear = calendar.get(Calendar.YEAR);
        this.currentMonth = calendar.get(Calendar.MONTH) + 1;
        this.currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        wheelView1.setCurrentItem(currentYear - 1900);
        wheelView2.setCurrentItem(currentMonth - 1);
        int dayNum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        // 清空天数
        days.clear();
        for (int i = 1; i <= dayNum; i++) {
            days.add(i);
        }
        wheelView3.setViewAdapter(new MyWheelAdapter(mContext, days, 3));
        wheelView3.setCurrentItem(currentDay - 1);
    }

    public String getDateStr() {
        return currentYear + "-" + currentMonth + "-" + currentDay;
    }

    class MyWheelAdapter extends AbstractWheelTextAdapter {

        private List<Integer> data;
        private int type;

        protected MyWheelAdapter(Context context, List<Integer> data, int type) {
            super(context, R.layout.wheel_item, NO_RESOURCE);
            // TODO Auto-generated constructor stub
            setItemTextResource(R.id.tvItem);
            this.data = data;
            this.type = type;
        }

        @Override
        public int getItemsCount() {
            // TODO Auto-generated method stub
            return data.size();
        }

        @Override
        protected CharSequence getItemText(int index) {

            String str = "";
            switch (type) {
                case 1:
                    str = context.getString(R.string.year);
                    break;
                case 2:
                    str = context.getString(R.string.month);
                    break;
                case 3:
                    str = context.getString(R.string.day2);
                    break;

                default:
                    break;
            }

            return "" + data.get(index) + str;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }
    }

    public void onItemClicked(WheelView wheel, int itemIndex) {
        // TODO Auto-generated method stub
        wheel.setCurrentItem(itemIndex);
    }

    private int getMAX_DAY_OF_MONTH(int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.MONTH, month - 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == wheelView1) {
            // 年份
            currentYear = newValue + 1900;

            //			Calendar calendar = Calendar.getInstance();
            //			calendar.set(Calendar.YEAR, currentYear);
            //			calendar.set(Calendar.MONTH, currentMonth - 1);

            days.clear();
            int dayNum = getMAX_DAY_OF_MONTH(currentMonth);
            for (int i = 1; i <= dayNum; i++) {
                days.add(i);
            }

            wheelView3.setViewAdapter(new MyWheelAdapter(mContext, days, 3));
            if (currentDay > dayNum) {
                wheelView3.setCurrentItem(dayNum - 1);
            } else {
                wheelView3.setCurrentItem(currentDay - 1);
            }
        }

        if (wheel == wheelView2) {
            currentMonth = newValue + 1;
            //			Calendar calendar = Calendar.getInstance();
            //			calendar.set(Calendar.YEAR, currentYear);
            //			calendar.set(Calendar.MONTH, currentMonth - 1);
            days.clear();
            int dayNum = getMAX_DAY_OF_MONTH(currentMonth);
            for (int i = 1; i <= dayNum; i++) {
                days.add(i);
            }

            wheelView3.setViewAdapter(new MyWheelAdapter(mContext, days, 3));
            if (currentDay > dayNum) {
                wheelView3.setCurrentItem(dayNum - 1);
            } else {
                wheelView3.setCurrentItem(currentDay - 1);
            }

        }

        if (wheel == wheelView3) {
            currentDay = newValue + 1;
        }
    }

    public interface DateSelectListener {
        void dateSelect(Calendar clCalendar);
    }
}
